package com.ygqh.baby.controller.utils;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Header;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.Assert;

import freemarker.cache.StringTemplateLoader;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateHashModel;

public class DocumentHandler {

	private static Configuration configuration = null;

	static {
		configuration = new Configuration(Configuration.VERSION_2_3_21);
		configuration.setDefaultEncoding("utf-8");
	}
		
	public static void generateByteArrayOutputStream(String str,OutputStream outStream) throws Exception{
		ByteArrayInputStream is = new ByteArrayInputStream(str.getBytes("UTF-8"));
		
		byte[] data = new byte[1024];
		
		int count = -1;
		while ((count = is.read(data, 0, 1024)) != -1){
			outStream.write(data, 0, count); 
		}		
		data = null;		
	}
		
	
	
	//指定要在ftl页面使用的静态包名	
	public static TemplateHashModel useStaticPackage(String packageName) {
		try {
			BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
			TemplateHashModel staticModels = wrapper.getStaticModels();
			TemplateHashModel fileStatics = (TemplateHashModel) staticModels
					.get(packageName);
			return fileStatics;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	public static byte[] createDocument(byte[] contents, Map<String, Object> dataMap)
			throws Exception {
		ByteArrayOutputStream ba = new ByteArrayOutputStream();

			XLSTransformer transformer = new XLSTransformer();
			InputStream inputStream = new ByteArrayInputStream(contents);
			// 开始填数 ...
			Workbook workbook = transformer.transformXLS(inputStream, dataMap);
			// 其它处理
			Sheet sheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
			Header header = sheet.getHeader();
			String headerStr = header.getLeft();
			if (StringUtils.isNotEmpty(headerStr)) {
				header.setLeft(ELUtils.evaluate(headerStr, dataMap).toString());
			}
			headerStr = header.getCenter();
			if (StringUtils.isNotEmpty(header.getCenter())) {
				header.setCenter(ELUtils.evaluate(headerStr, dataMap).toString());
			}
			if (StringUtils.isNotEmpty(header.getRight())) {
				header.setRight(ELUtils.evaluate(header.getRight(), dataMap).toString());
			}						
			Sheet activeSheet = workbook.getSheetAt(workbook.getActiveSheetIndex());
			
			//自动行高
			POIUtils.autoRowHeight(activeSheet);
			// 生成字节流
			POIUtils.writeWorkbook(workbook, ba);		
			byte[] bytes = ba.toByteArray();
			ba.close();

		return bytes;
	}
	
	
	

	
	public static void createDownload(byte[] bytes, String fileName, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// 如果想出来让IE提示你是打开还是保存的对话框，加上下面这句就可以了
			String attachmentName = fileName;
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
				attachmentName = URLEncoder.encode(attachmentName, "UTF-8");
			} else {
				attachmentName = new String(attachmentName.getBytes("UTF-8"), "ISO8859-1");
			}			
			ByteArrayOutputStream ba = new ByteArrayOutputStream();
			ba.write(bytes);
			//response.setHeader("Content-disposition", "attachment; filename=" + attachmentName);  //弹出保存对话框的
			response.setHeader("Content-disposition", "inline; filename=" + attachmentName);//直接打开
			response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
			response.setHeader("Pragma", "public");
			response.setDateHeader("Expires", (System.currentTimeMillis() + 1000));
			response.setContentLength(ba.size());
			response.setContentType("application/octet-stream");

			ServletOutputStream out = response.getOutputStream();
			ba.writeTo(out);
			out.flush();
			out.close();
			ba.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	public static void DownloadExcel(byte[] fileTemplate,String fileName, Map<String,Object> dataMap, HttpServletRequest request, HttpServletResponse response) {
		try {
			
			byte[] bytes = createDocument(fileTemplate, dataMap);
			createDownload(bytes,fileName,request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
}